package com.ikangtai.shecare.personal;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.DownloadService;
import com.ikangtai.shecare.common.baseView.ListBar;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.eventBusMsg.FoundNewVersionByHandMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.QRUtils;
import com.ikangtai.shecare.common.util.UpdateUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

public class AboutActivity extends BaseActivity implements View.OnClickListener {

    private TopBar topBar;
    private ImageView twoDemension_code_logo;
    private ListBar officialSite;
    private ListBar version;
    private ListBar serviceWX;
    private ListBar checkVersion;
    private static final String OFFICIAL_SITE_URL = "http://www.ikangtai.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_personal_about);

        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });

        twoDemension_code_logo = (ImageView) findViewById(R.id.twoDemension_code_logo);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) twoDemension_code_logo.getLayoutParams();
        int imgWidth = layoutParams.width;//设置高度

        try {
            Bitmap bitmap = QRUtils.encodeToQRWidth("http://www.ikangtai.com/shecare_download.html", imgWidth);//要生成二维码的内容，我这就是一个网址
            twoDemension_code_logo.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
            //Toast.makeText(this, "生成二维码失败", Toast.LENGTH_SHORT);
        }

        officialSite = (ListBar) findViewById(R.id.official_site);
        officialSite.setOnClickListener(this);
        findViewById(R.id.feedback).setOnClickListener(this);
        version = (ListBar) findViewById(R.id.version);
        version.setRightText(getVersion());
        serviceWX = (ListBar) findViewById(R.id.serviceWX);

        findViewById(R.id.checkVersion).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.official_site:
                Uri officialSiteUri = Uri.parse(OFFICIAL_SITE_URL);
                Intent officialSiteIntent = new Intent(Intent.ACTION_VIEW, officialSiteUri);
                startActivity(officialSiteIntent);
                break;
            case R.id.feedback:
                Intent feedBackIntent = new Intent(this, AboutFeedbackActivity.class);
                startActivity(feedBackIntent);
                break;
            case R.id.serviceWX:
                break;
            case R.id.checkVersion:
                checkAppVersion();
                break;
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        AppLog.i("getVersion in AboutActivity!");
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }

    /**
     * 检查版本更新
     */
    private void checkAppVersion() {
        OKHttpUtil okHttpUtil = new OKHttpUtil(this);
        final UpdateUtil updateUtil = new UpdateUtil(this);

        String appendUrl = "product/getNewVersionInfo.json?OSType=Android&DevType=" + updateUtil.getDevType();

        okHttpUtil.getAsync(appendUrl, okHttpUtil.new BaseCallBack() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                FoundNewVersionByHandMsg foundNewVersionByHandMsg = new FoundNewVersionByHandMsg();
                try {
                    JSONObject respJSONObj = new JSONObject(response.body().string());
                    int respCode = respJSONObj.getInt("code");
                    if (200 == respCode) {
                        AppLog.i("start compare version!");
                        int serverVersionCode = respJSONObj.getInt("versionCode");
                        int localVersionCode = updateUtil.getVerCode();
                        AppLog.i("localVersionCode = " + localVersionCode + ", serverVersionCode = " + serverVersionCode);

                        if (localVersionCode < serverVersionCode) {
                            AppLog.i("found new version! localVersionName = " + updateUtil.getVerName() + ", serverVersionName = " + respJSONObj.getString("version"));

                            String updateBaseURL = respJSONObj.getString("updateURL");
                            String updateURL = updateBaseURL + UpdateUtil.getChannelAPKName(AboutActivity.this);

                            AppLog.i("updateURL = " + updateURL);

                            String updateList = respJSONObj.getString("updates");

                            foundNewVersionByHandMsg.setHasNewVersion(true);
                            foundNewVersionByHandMsg.setDownloadURL(updateURL);
                            foundNewVersionByHandMsg.setUpdateList(updateList);
                            AppLog.i("updateURL = " + updateURL + ", updateList = " + updateList);

                        } else {
                            foundNewVersionByHandMsg.setHasNewVersion(false);
                        }
                        EventBus.getDefault().post(foundNewVersionByHandMsg);
                    } else {
                        AppLog.i("checkAppVersion onResponse respCode failed! is:" + respCode);
                    }
                } catch (JSONException e) {
                    AppLog.i("checkAppVersion onResponse failed! JSONException!");
                    e.printStackTrace();
                }
            }
        });
    }

    @Subcriber
    private void foundNewAppVersionByHand(FoundNewVersionByHandMsg foundNewVersionByHandMsg) {

        if (foundNewVersionByHandMsg.isHasNewVersion()) {
            final String downloadURL = foundNewVersionByHandMsg.getDownloadURL();
            String updateList = foundNewVersionByHandMsg.getUpdateList();

            String formatUpdateList = getFormatUpdateList(updateList);

            String updateAlertTitle = getString(R.string.updateAlertTitle);
            String updateAlertMsg = getString(R.string.updateAlertMsg);
            String updateAlertPositiveButtonTxt = getString(R.string.updateAlertPositiveButtonTxt);
            String updateAlertNegativeButtonTxt = getString(R.string.updateAlertNegativeButtonTxt);

            Dialog dialog = new AlertDialog.Builder(this).setTitle(updateAlertTitle)
                    .setMessage(updateAlertMsg + formatUpdateList)
                    .setCancelable(false)
                    .setPositiveButton(updateAlertPositiveButtonTxt, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            downloadAPK(downloadURL);
                        }
                    })
                    .setNegativeButton(updateAlertNegativeButtonTxt, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                        }
                    }).create();
            dialog.show();
        } else {
            Toast.makeText(this, getString(R.string.alreadyLatestVersion), Toast.LENGTH_SHORT).show();
        }
    }

    private String getFormatUpdateList(String updateList) {

        AppLog.i("new version updateList = " + updateList);

        String formatUpdateList = "\n";
        try {
            JSONArray updateListJSONArray = new JSONArray(updateList);

            for (int i = 0; i < updateListJSONArray.length(); i++) {
                JSONObject updateJSONObj = (JSONObject) updateListJSONArray.get(i);
                formatUpdateList += updateJSONObj.getString("update") + "\n";
            }

        } catch (JSONException e) {
            AppLog.i("JSONException e = " + e.getMessage());
        }

        return formatUpdateList;
    }

    private void downloadAPK(String downloadURL) {
        AppLog.i("start downloading apk from url = " + downloadURL);
        Intent intent = new Intent(this, DownloadService.class);
        intent.putExtra("downloadURL", downloadURL);
        this.startService(intent);
    }
}
